//
//  QRCodeViewController.swift
//  JKWeiBo
//
//  Created by 王冲 on 2017/6/4.
//  Copyright © 2017年 希爱欧科技有限公司. All rights reserved.
//

import UIKit
import AVFoundation

class QRCodeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        /*
         * 状态栏左右按钮
         */
         nav()
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        
        super.viewWillAppear(animated)
        view.backgroundColor = UIColor(white: 0.0, alpha: 1)
    }
    
    // MARK: 自定义导航栏的添加
    private func nav(){
        
      
      
      view.addSubview(navView)
    
        // 1.添加左右的*关闭*和*相册*按钮
        let btnLeft = UIButton.createButton(tittleName: "关闭", tittleColor: UIColor.orange, target: self, action: #selector(QRCodeViewController.leftbtn))
        btnLeft.x = 12
        btnLeft.y = 20
        navView.addSubview(btnLeft)
        
        let btnRight = UIButton.createButton(tittleName: "相册", tittleColor: UIColor.orange, target: self, action: #selector(QRCodeViewController.rightbtn))
        btnRight.x = JKscreenW-12-btnLeft.width
        btnRight.y = 20
        navView.addSubview(btnRight)
        
        // 2.添加中间的标题按钮
        navView.addSubview(labelTittle)
        
        // 3.添加 botoomView
        view.addSubview(botoomView)
        
        botoomView.addSubview(qrCode)
        qrCode.x = 20
        qrCode.y = (49-qrCode.height)/2.0
    
        botoomView.addSubview(barCode)
        barCode.x = JKscreenW - barCode.width-20
        barCode.y = (49-barCode.height)/2.0
        
        // 4. 添加中间的二维码
        view.addSubview(qrViewBackGround)
        qrViewBackGround.addSubview(backInage)
        qrViewBackGround.addSubview(chongjibo)
       
        // 5. 添加我的名片按钮
        view.addSubview(myCard)
        myCard.centerX = JKscreenW/2.0
        myCard.y = botoomView.frame.minY - 60

    }
    
    // MARK: 5.在视图显示出来以后 冲击波动画的添加
    override func viewDidAppear(_ animated: Bool) {
        
        super.viewDidAppear(animated)
        
        // 添加冲击波
        addLayerAnimationTranformTranslationY(layer: self.chongjibo.layer, fromalue: 0, toValue: 600)
        
        // 开始扫描
        startScan()
    
    }
    
    // MARK: 开始扫描
    private func startScan(){
    
        // 1.判断是否能够将输入添加到会话中
        if !session.canAddInput(deviceInput)
        {
          return
        }
        // 2.判断是否能够将输出添加到会话中
        if !session.canAddOutput(deviceOutput)
        {
          return
        }
        // 3.将输入和输出添加到会话中
        session.addInput(deviceInput)
        //print(output.metadataObjectTypes)
        session.addOutput(deviceOutput)
        // 4.设置输出能够解析的数据类型
        // 注意: 设置输出能够解析的数据类型,一定要在输出对象添加到会话之后设置，否则会报错
        // 设置系统所有的数据类型都能解析
        deviceOutput.metadataObjectTypes = deviceOutput.availableMetadataObjectTypes
        // 5.设置输出对象的代理，只要解析成功就会通知代理
        deviceOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
        // 6.添加预览图层,也就是把摄像头照到的地方显示出来
        view.layer.insertSublayer(previewLayer, at: 0)
        // 6.1.把绘制图层添加到预览图层上
        previewLayer.addSublayer(drawLayer)
        // 7.开始扫描
        session.startRunning()
        
        
    
    }
    
    //纵向移动（沿着Y轴） transform.translation.y
    func addLayerAnimationTranformTranslationY(layer: CALayer,fromalue:Int,toValue:Int) {
        let animation = CABasicAnimation(keyPath: "transform.translation.y")
        animation.fromValue = fromalue
        animation.toValue = toValue
        animation.duration = 2.0
        animation.repeatCount = MAXFLOAT
        //这里我们可以添加可以不添加，添加一个缓慢进出的动画效果(int/out)。当不添加时，匀速运动，会使用kCAMediaTimingFunctionLinear；当添加时，layer会在开始和结束时比较缓慢
        animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
        
        layer.add(animation, forKey: "addLayerAnimationTranformTranslationY")
    }
    
    // MARK: 关闭按钮的点击
    func leftbtn(){
    
      dismiss(animated: true, completion: nil)
    
    }
    
    // MARK: 相册的点击
    func rightbtn() {
        
        print("相册")
        
    }

    // MARK: 导航栏的创建
    private lazy var navView: UIView = {
        
        let navview = UIView()
        navview.frame = CGRect(x: 0, y: 0, width: JKscreenW, height: 64)
        navview.backgroundColor = UIColor(white: 0.0, alpha: 0.9)
        return navview
        
    }()
    
    // MARK: 标题按钮的创建
    private lazy var labelTittle: UILabel = {
    
        let label = UILabel(frame: CGRect(x: JKscreenW/2-50, y: 20, width: 100, height: 30))
        label.textAlignment = NSTextAlignment.center
        label.text = "扫一扫"
        label.font = UIFont.systemFont(ofSize: 15)
        label.textColor = UIColor.white
        //label.backgroundColor = UIColor.brown
        return label
    
    }()
    
    // MARK: 底部导航条的创建
    private lazy var botoomView: UIView = {
        
        let navview = UIView()
        navview.frame = CGRect(x: 0, y: JKscreenH-49, width: JKscreenW, height: 49)
        navview.backgroundColor = UIColor(white: 0.0, alpha: 0.9)
        return navview
        
    }()
    
    
    // MARK: 二维码点击
    func qrCodeClicked(qrBtn:UIButton){
        
        print("二维码")
        qrBtn.isSelected = true
        barCode.isSelected = false
        self.chongjibo.layer.removeAllAnimations()
        qrViewBackGround.height = 300
        backInage.height = 300
        chongjibo.height = 300
        chongjibo.y = -300
        addLayerAnimationTranformTranslationY(layer: self.chongjibo.layer, fromalue: 0, toValue: 600)
        
        
        
    }
    // MARK: 条形码点击
    func barCodeClicked(brBtn:UIButton){
        
        print("条形码")
        brBtn.isSelected = true
        qrCode.isSelected = false
        qrViewBackGround.height = 150
        backInage.height = 150
        chongjibo.height = 150
        chongjibo.y = -150
        //添加冲击波
        addLayerAnimationTranformTranslationY(layer: self.chongjibo.layer, fromalue: 0, toValue: 300)
    }
    
    private lazy var myCard: UIButton = {
    
       let mycard = UIButton()
        mycard.frame = CGRect(x: 0, y: 0, width: 100, height: 30)
        mycard.backgroundColor = UIColor.white
        mycard.layer.cornerRadius = 15
        mycard.setTitle("我的名片", for: UIControlState.normal)
        mycard.setTitleColor(UIColor.JKTextGayColor(), for: UIControlState.normal)
        mycard.addTarget(self, action: #selector(QRCodeViewController.clickMycard), for: UIControlEvents.touchUpInside)
        return mycard;
    
    }()
    
    // MARK: 我的名片点击中
    func clickMycard() {
        
        print("我的名片")
        let qRCodeCardViewController = QRCodeCardViewController()
        qRCodeCardViewController.modalTransitionStyle = UIModalTransitionStyle.flipHorizontal
        present(qRCodeCardViewController, animated: true, completion: nil)
       
    }
    
    // MARK: 二维码
    private lazy var qrCode: UIButton = {
    
        let qrcode = UIButton.createButtonImage(imageName: "qrcode_tabbar_icon_qrcode", target: self, action: #selector(QRCodeViewController.qrCodeClicked(qrBtn:)))
        qrcode.isSelected = true
         return qrcode
    
    }()
    
    // MARK: 条形码
    private lazy var barCode: UIButton = {
        
        let barcode = UIButton.createButtonImage(imageName: "qrcode_tabbar_icon_barcode", target: self, action: #selector(QRCodeViewController.barCodeClicked(brBtn:)))
        return barcode
        
    }()
    
    // MARK: 中间的二维码添加
    private lazy var qrViewBackGround: UIView = {
    
        let qrView = UIView()
        qrView.frame = CGRect(x: JKscreenW/2.0-150, y: JKscreenH/2.0-150, width: 300, height: 300)
        qrView.clipsToBounds = true
        //qrView.backgroundColor = UIColor.red
        return qrView
    
    }()
    
    // MARK: 冲击波图片的添加
    private lazy var backInage: UIImageView = {
    
        let bianimageView = UIImageView(image: UIImage(named: "qrcode_border"))
        bianimageView.frame = CGRect(x: 0, y: 0, width: 300, height: 300)
        return bianimageView
    
    }()
    
    // MARK: 冲击波的添加
    private lazy var chongjibo: UIImageView = {
    
        let chongji = UIImageView(image: UIImage(named: "qrcode_scanline_qrcode"))
        chongji.frame = CGRect(x: 0, y: -300, width: 300, height: 300)
        return chongji
    
    }()
    
    // MARK: 懒加载关于二维码扫描的一些知识
    // 1.拿到会话
    private lazy var session: AVCaptureSession = AVCaptureSession()
    
    // 2.拿到输入设备
    private lazy var deviceInput: AVCaptureInput? = {
    
        // 获取摄像头
        let device = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
    
        do{
           // 创建输入对象
           let input = try AVCaptureDeviceInput(device: device)
           return input

        }catch{
        
          return nil
        
        }
        
    }()
    
    // 3.拿到输出对象
    private lazy var deviceOutput: AVCaptureMetadataOutput =  AVCaptureMetadataOutput()
    
    // 4.创建预览图层
    lazy var previewLayer: AVCaptureVideoPreviewLayer = {
    
        let layer = AVCaptureVideoPreviewLayer(session: self.session)
        layer?.frame = UIScreen.main.bounds
        return layer!
    
    }()
    
    // 5.创建用于绘制边线的图层
    lazy var drawLayer: CALayer = {
    
        let drawlayer = CALayer()
        drawlayer.frame = UIScreen.main.bounds
        return drawlayer
    
    }()
  
}

// MARK: 相册扫描的代理方法回调
extension QRCodeViewController: AVCaptureMetadataOutputObjectsDelegate{

    func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!){
    
        // 1.获取扫描到的数据
        guard let objc = metadataObjects.last as? AVMetadataMachineReadableCodeObject
            else {
                
            return
        }
        
        // 打印最后的值
        print(objc.stringValue)
        
        // 2.获取扫描到的二维码的位置
        // 2.1.转换坐标
        //for object in metadataObjects {
            
            // 2.1.2.将坐标界面转化为可识别的类型
            //let codeObject = previewLayer.transformedMetadataObject(for: object as! AVMetadataObject) as! AVMetadataMachineReadableCodeObject
       
            //print(codeObject)
            
            // 2.1.3.绘制图形 暂时关闭 绘制图形
            //drawCorners(codeObject: codeObject)
        //}
    
    }

    // MARK: 绘制图形
    /*
     * codeObject
     */
    private func drawCorners(codeObject: AVMetadataMachineReadableCodeObject){
        
        if codeObject.corners.isEmpty {
            return
        }
        
        clearDrawLayer()
        
        // 1.创建一个图层
        let layer = CAShapeLayer()
        layer.lineWidth = 2
        layer.strokeColor = UIColor.red.cgColor
        layer.fillColor = UIColor.clear.cgColor
        
        // 2.创建路径
        //layer.path = UIBezierPath(rect: CGRect(x: 100, y: 100, width: 200, height: 200)).cgPath
        layer.path = cornersPath(corners: codeObject.corners as NSArray)
        
        // 3.将绘制好的图层添加到drawLayer
        drawLayer.addSublayer(layer)
    }
    
    private func cornersPath(corners: NSArray) -> CGPath {
        let path = UIBezierPath()

        
        // 1. 移动到第一个点
        var index = 0
        index = index + 1
 
        path.move(to: CGPoint(dictionaryRepresentation: corners[0] as! CFDictionary)!)
        
        print(corners.count)
        
        // 2. 遍历剩余的点
        while index < corners.count {
        
            path.addLine(to: CGPoint(dictionaryRepresentation: corners[index] as! CFDictionary)!)
            index = index + 1
            print(index)
        }
        
        // 3. 关闭路径
        path.close()
        
        return path.cgPath
    }
    
    /// 清空绘图图层
    private func clearDrawLayer() {
        if drawLayer.sublayers == nil {
            return
        }
        
        for layer in drawLayer.sublayers! {
            layer.removeFromSuperlayer()
        }
    }
    
    
    
}



